<template>
  <div class="mod-config" ref="tableForm">
    <el-button-group style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
      <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
      <el-button type="primary" @click="printInfo">导出成Excel</el-button>
    </el-button-group>
    <!-- 查询搜索框 -->
    <el-form inline :model="dataForm" label-width="100px" @keyup.enter.native="searchHandle">
      <el-form-item label="查询角度">
        <el-radio-group v-model="dataForm.queryPoint" @change="queryPointChangeHandle">
          <el-radio label="3">条码</el-radio>
          <el-radio label="1">商品</el-radio>
          <el-radio label="2">品种</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="品种零售价">
        <el-radio v-model="dataForm.groupFlag" label="1">分组</el-radio>
        <el-radio v-model="dataForm.groupFlag" label="2">不分组</el-radio>
      </el-form-item>
      <el-form-item label="筛选库存信息">
        <el-select v-model="dataForm.quantityCheck">
          <el-option v-for="item in quantityCheckOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品编码">
        <el-input v-model="dataForm.goodsCode"></el-input>
      </el-form-item>
      <el-form-item label="商品条码">
        <el-input v-model="dataForm.goodsBarcode"></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="dataForm.goodsName"></el-input>
      </el-form-item>
      <el-form-item label="商品类别">
        <el-select v-model="dataForm.ctgId" clearable>
          <el-option v-for="item in ctgOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="制造商">
        <el-input v-model="dataForm.supplyName">
          <el-button slot="append" @click="supplySearchHandle">选择</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="品种">
        <el-input v-model="dataForm.brandName">
          <el-button slot="append" @click="brandSearchHandle">选择</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="球镜范围" v-if="dataForm.ctgId == '8'">
        <el-row class="row-range">
          <el-col :span="11">
            <el-input v-model="dataForm.mirrorBallMin"></el-input>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.mirrorBallMax"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="厂家型号" v-if="dataForm.ctgId == '1' || dataForm.ctgId == '6' || dataForm.ctgId == '8'">
        <el-input v-model="dataForm.manufacturerSpec"></el-input>
      </el-form-item>
      <el-form-item label="厂家色号" v-if="dataForm.ctgId == '1' || dataForm.ctgId == '6' || dataForm.ctgId == '8'">
        <el-input v-model="dataForm.manufacturerColorNumber"></el-input>
      </el-form-item>
      <el-form-item label="尺寸" v-if="dataForm.ctgId != '8'">
        <el-input v-model="dataForm.goodsSize"></el-input>
      </el-form-item>
      <el-form-item label="工艺类型" v-if="dataForm.ctgId == '1'">
        <el-select v-model="dataForm.craftType" clearable>
          <el-option v-for="item in craftTypeData" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="镜架材质" v-if="dataForm.ctgId == '1'">
        <el-select v-model="dataForm.frameMaterial" clearable>
          <el-option v-for="item in frameMaterialData" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购年份" v-if="dataForm.ctgId == '1'">
        <el-input v-model="purchaseDate" placeholder="年份后两位+两位月份"></el-input>
      </el-form-item>
      <el-form-item label="配件类型" v-if="dataForm.ctgId == '2'">
        <el-select v-model="dataForm.accessoriesType" clearable>
          <el-option v-for="item in bizData.accessoryTypeData" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="材料分类" v-if="dataForm.ctgId == '3'">
        <el-select v-model="dataForm.lensMaterial" clearable>
          <el-option v-for="item in bizData.lensMaterial" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="折射率" v-if="dataForm.ctgId == '3'">
        <el-select v-model="dataForm.refractiveIndex" clearable>
          <el-option v-for="item in bizData.refractivityData" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="镜片分类" v-if="dataForm.ctgId == '3'">
        <el-select v-model="dataForm.photometricClassification" clearable>
          <el-option v-for="item in bizData.photometricClassification" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用类型" v-if="dataForm.ctgId == '4'">
        <el-select v-model="dataForm.useType" clearable>
          <el-option v-for="item in bizData.useType" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="抛弃类型" v-if="dataForm.ctgId == '4'">
        <el-select v-model="dataForm.disusedClassification" clearable>
          <el-option v-for="item in bizData.disusedClassification" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="球镜范围" v-if="dataForm.ctgId == '3' || dataForm.ctgId == '4'">
        <el-row class="row-range">
          <el-col :span="11">
            <el-input v-model="dataForm.mirrorBallMin"></el-input>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.mirrorBallMax"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="柱镜范围" v-if="dataForm.ctgId == '3' || dataForm.ctgId == '4'">
        <el-row class="row-range">
          <el-col :span="11">
            <el-input v-model="dataForm.columnMirrorMin"></el-input>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.columnMirrorMax"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="定做状态" v-if="dataForm.ctgId == '3' || dataForm.ctgId == '4'">
        <el-select v-model="dataForm.customizeType" clearable>
          <el-option v-for="item in bizData.customizeTypeData" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="仓位名称">
        <el-select v-model="dataForm.stockIds" multiple collapse-tags @change="changeSelect" style="width: 249px" v-if="this.radio != '2'">
          <el-checkbox v-model="checked" @change='selectAll'>全选</el-checkbox>
          <el-option v-for="item in stockOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
        </el-select>
        <el-radio-group v-model="radio" style="margin-left: 15px;" @change="changeStock">
          <el-radio :label="'2'">不分仓</el-radio>
          <el-radio :label="'1'">启用仓</el-radio>
          <el-radio :label="'0'">停用仓</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="dataForm.status" clearable>
          <el-option v-for="item in statusOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="零售价格">
        <el-row class="row-range">
          <el-col :span="11">
            <el-input v-model="dataForm.goodsPriceMin"></el-input>
          </el-col>
          <el-col class="line" :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.goodsPriceMax"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="库存预警状态">
        <el-select v-model="dataForm.warningStatus">
          <el-option v-for="item in warningStatusOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查询年月">
        <el-col :span="12">
          <el-date-picker v-model="dataForm.yearMonth" class="timePicker" type="month" placeholder="选择日期" format="yyyy-MM" value-format="yyyy-MM">
          </el-date-picker>
        </el-col>
      </el-form-item>
    </el-form>
    <div class="avue-crud">
      <el-table :data="dataList" height="calc(100vh - 205px)" ref="table" border show-summary :summary-method="getSummaries" v-loading="dataListLoading" :max-height="tableHeight">
        <el-table-column key="1" label="商品编码" width="180" fixed="left" v-if="dataForm.queryPoint == '1'">
          <template slot-scope="scope">
            <el-button type="text" @click="getDetailByCheck(scope.row)">{{scope.row.goodsCode}}</el-button>
          </template>
        </el-table-column>
        <el-table-column key="2" label="品种编码" width="180" fixed="left" v-if="dataForm.queryPoint == '2'">
          <template slot-scope="scope">
            <el-button type="text" @click="checkGoodsByBrand(scope.row)">{{scope.row.goodsCode}}</el-button>
          </template>
        </el-table-column>
        <el-table-column key="3" prop="goodsBarcode" label="商品条码" width="160" v-if="this.dataForm.queryPoint == 3"
          fixed="left"></el-table-column>
        <el-table-column key="4" prop="goodsName" label="商品名称" v-if="this.dataForm.queryPoint == 1 || this.dataForm.queryPoint == 3"
          min-width="230" fixed="left"></el-table-column>
        <el-table-column key="5" prop="brandName" label="品种名称" v-if="this.dataForm.queryPoint == 2" min-width="230"
          fixed="left"></el-table-column>
        <el-table-column key="6" prop="goodsQuantity" label="数量" width="100"></el-table-column>
        <el-table-column key="7" prop="goodsPrice" label="标准零售价" width="100" v-if="dataForm.groupFlag != '2' || dataForm.queryPoint != '2'"></el-table-column>
        <el-table-column key="8" prop="ctgName" label="商品类别" width="80"></el-table-column>
        <el-table-column key="9" prop="supplyName" label="制造商" width="100"></el-table-column>
        <el-table-column key="10" prop="stockName" label="仓位" width="200"></el-table-column>
        <el-table-column key="11" prop="batch" label="批次" width="100"></el-table-column>
        <el-table-column key="12" prop="invalidTime" label="效期" width="110"></el-table-column>
      </el-table>
    </div>
    <div class="avue-crud__pagination" style="margin-bottom: 25px;margin-top: 0;">
      <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
      </el-pagination>
    </div>
    <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
    <search-brand v-if="brandVisible" ref="brandDialog" @refreshData="getBrandData"></search-brand>
    <goods-info v-if="infoVisible" ref="info"></goods-info>
    <CheckGoods v-if="goodsVisible" ref="goodsDialog"></CheckGoods>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { filterParams } from '@/util/tools'
  import { remote } from '@/api/admin/dict'
  import { getMonthStoragePage, getBeginOfMonthStorageExport, getStorageMonthGoodsNumberSum } from '@/api/eims/storage'
  import { getCtgList } from '@/api/eims/ctg'
  import { getStockList } from '@/api/eims/stock'

  import GoodsInfo from '../goodsInfo/detail'
  import SearchSupply from '@/components/business/SearchSupply'
  import SearchBrand from '@/components/business/SearchBrand'
  import CheckGoods from './CheckGoodsByBrand.vue'
  
  export default {
    data() {
      return {
        infoVisible: false,
        checked: false,
        frameMaterialData: [],
        craftTypeData: [],
        dataForm: {
          quantityCheck: 1,
          queryPoint: '1',
          groupFlag: '1',
          yearMonth: '',
          stockIds: []
        },
        radio: '1',
        allGoodsNum: '',
        dataList: [],
        pageIndex: 1,
        pageSize: 200,
        totalPage: 0,
        ctgOptions: [],
        stockOptions: [],
        oldStockIds: [],
        quantityCheckOptions: [
          { label: '显示库存所有的商品', value: 0 },
          { label: '忽略库存为0的商品', value: 1 },
          { label: '显示库存=0的商品', value: 2 },
          { label: '显示库存>0的商品', value: 3 },
          { label: '显示库存<0的商品', value: 4 }
        ],
        statusOptions: [{ label: '启用', value: '1' }, { label: '停用', value: '0' }
        ],
        warningStatusOptions: [
          { label: '小于等于红色预警', value: 1 },
          { label: '大于红色预警小于库存量下限', value: 2 },
          { label: '大于等于库存量下限并小于等于库存量上限', value: 3 },
          { label: '大于库存量上限', value: 4 }
        ],
        dataListLoading: false,
        supplyVisible: false,
        brandVisible: false,
        goodsVisible: false
      }
    },
    components: {
      SearchSupply,
      SearchBrand,
      GoodsInfo,
      CheckGoods
    },
    computed: {
      ...mapGetters(['permissions', 'bizData']),
      tableHeight: function(){
        return window.innerHeight - 260
      }
    },
    methods: {
      //excel模式导出
      printInfo() {
        let params2 = filterParams(this.dataForm)
        getBeginOfMonthStorageExport(params2).then(response => {
            var blob = new Blob([response.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
              var a = document.createElement('a');
              a.download = "月初库存表.xlsx";
              a.href = URL.createObjectURL(blob);
              a.click();
            }
        })
      },
      //  查询数据
      searchHandle() {
        remote('frame_material').then(response => {
          this.frameMaterialData = response.data.data
        })
        remote('craft_type').then(response => {
          this.craftTypeData = response.data.data
        })
        this.pageIndex = 1
        this.getDataList()
        this.getCtgOptions()
        this.getStockOptions()
      },
      //  清空查询查询表单
      searchReset() {
        for (let key in this.dataForm) {
          if (key == 'queryPoint') {
            this.dataForm[key] = '1'
          } else if (key == 'groupFlag') {
            this.dataForm[key] = '1'
          } else if (key == 'quantityCheck') {
            this.dataForm[key] = 1
          } else {
            this.dataForm[key] = ''
          }
        }
      },
      //  查询角度
      queryPointChangeHandle(val) {
        if (val == '3') {
          // this.dataForm.ctgId = 1
          this.$set(this.dataForm, 'ctgId', 1)
        }
        this.getDataList()
      },
      // 获取数据列表
      getDataList() {
        // this.dataForm.quantityCheck = 1;
        if (this.dataForm.queryPoint == 3) {
          if (!this.dataForm.ctgId) {
            this.$message.warning('请选择商品类型')
            return
          }
        }
        if (this.dataForm.ctgId == '3' || this.dataForm.ctgId == '4') {
          this.dataForm.customizeType = this.dataForm.customizeType
        }
        let params1 = {
          current: this.pageIndex,
          size: this.pageSize
        }
        let params2 = filterParams(this.dataForm)
        this.dataListLoading = true
        getStorageMonthGoodsNumberSum(filterParams(this.dataForm)).then(response => {
          if(response.data.code == '0'){
            this.allGoodsNum = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
        getMonthStoragePage(Object.assign(params1, params2)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
          this.$nextTick(() => {
            this.$refs.table.doLayout()
          })
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
        this.$nextTick(() => {
          this.$refs.table.bodyWrapper.scrollTop = 0;
        })

      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
        this.$nextTick(() => {
          this.$refs.table.bodyWrapper.scrollTop = 0;
        })
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      //  获取商品类别列表
      getCtgOptions() {
        getCtgList().then(response => {
          if(response.data.code == '0'){
            this.ctgOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //  获取仓位列表
      getStockOptions() {
        let data = {
          status: this.radio
        }
        getStockList(data).then(response => {
          if(response.data.code == '0'){
            this.stockOptions = response.data.data
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      //仓位状态选择
      changeStock() {
        this.dataForm.stockIds = []
        this.getStockOptions()
      },
      //根据code获取商品详细信息
      getDetailByCheck(info) {
        let time = ''
        this.infoVisible = true
        this.$nextTick(() => {
          this.$refs.info.init(info, '商品信息', time, this.dataForm.stockIds)
        })
      },
      // 根据品种编码查看商品信息
      checkGoodsByBrand(row) {
        let time = ''
        this.goodsVisible = true
        this.$nextTick(() => {
          this.$refs.goodsDialog.init(row, time, this.dataForm.stockIds)
        })
      },
      //  查询制造商信息
      supplySearchHandle() {
        this.supplyVisible = true
        let ctgId = this.dataForm.ctgId || ''
        let data = {
          ctgId: ctgId
        }
        this.$nextTick(() => {
          this.$refs.supplyDialog.init(data)
        })
      },
      //  查询商品品种信息
      brandSearchHandle() {
        this.brandVisible = true
        let ctgId = this.dataForm.ctgId || ''
        if (!this.dataForm.supplyId) {
          this.$message.warning('请选择制造商')
          return
        }
        let data = {
          ctgId: ctgId,
          supplyId: this.dataForm.supplyId
        }
        this.$nextTick(() => {
          this.$refs.brandDialog.init(data)
        })
      },
      //  获取制造商信息
      getSupplyData(data) {
        this.$set(this.dataForm, 'supplyId', data.id)
        this.$set(this.dataForm, 'supplyName', data.name)
      },
      //  获取商品品种信息
      getBrandData(data) {
        this.$set(this.dataForm, 'brandId', data.id)
        this.$set(this.dataForm, 'brandName', data.name)
      },
      //  合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总库存合计:' + this.allGoodsNum
            return;
          }
          let idx = 0
          if (this.dataForm.queryPoint == '1' || this.dataForm.queryPoint == '2') {
            idx = 2
          } else {
            idx = 3
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            if (index == idx) {
              sums[index] = '合计：' + values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      },
      selectAll() {
        this.dataForm.stockIds = []
        if (this.checked) {
          this.stockOptions.map((item) => {
            this.dataForm.stockIds.push(item.id)
          })
        } else {
          this.dataForm.stockIds = []
        }
      },
      changeSelect(val) {
        if (val.length === this.stockOptions.length) {
          this.checked = true
        } else {
          this.checked = false
        }
      },
    }
  }
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
    // order: 1;
    z-index: 2;
  }

  .bg-row {
    padding-left: 5px;
    padding-top: 5px;
  }

  .el-checkbox {
    text-align: right;
    width: 100%;
    padding-right: 20px;
  }
</style>
